<template>
  <div>
    <el-tabs
      type="border-card"
      style="margin: 0 20px; height: 92.3vh"
      @tab-click="tabChange"
      v-model="$store.state.activeName7"
    >
      <el-tab-pane label="累计流量" name="累计流量">
        <el-form inline :model="form">
          <el-form-item label="开始时间">
            <el-date-picker
              type="datetime"
              placeholder="选择开始时间"
              size="mini"
              v-model="form.startTime"
              default-time="00:00:00"
              :picker-options="startTimePicker"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              type="datetime"
              placeholder="选择结束时间"
              size="mini"
              v-model="form.endTime"
              default-time="00:00:00"
              :picker-options="endTimePicker"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="query">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="week">一周</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="month">一月</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="all">全部</el-button>
          </el-form-item>
        </el-form>
        <div id="total" class="chart"></div>
      </el-tab-pane>
      <el-tab-pane label="变化量" name="变化量">
        <el-form inline :model="form2">
          <el-form-item label="开始时间">
            <el-date-picker
              type="datetime"
              placeholder="选择开始时间"
              size="mini"
              v-model="form2.startTime"
              default-time="00:00:00"
              :picker-options="startTimePicker2"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              type="datetime"
              placeholder="选择结束时间"
              size="mini"
              v-model="form2.endTime"
              default-time="00:00:00"
              :picker-options="endTimePicker2"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="query2">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="week2">一周</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="month2">一月</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" size="mini" @click="all2">全部</el-button>
          </el-form-item>
        </el-form>
        <div id="change" class="chart"></div>
        <div class="btns">
          <el-button plain type="warning" size="mini" @click="time(1)"
            >1小时</el-button
          >
          <el-button plain type="warning" size="mini" @click="time(2)"
            >2小时</el-button
          >
          <el-button plain type="warning" size="mini" @click="time(6)"
            >6小时</el-button
          >
          <el-button plain type="warning" size="mini" @click="time(12)"
            >12小时</el-button
          >
          <el-button plain type="warning" size="mini" @click="time(24)"
            >24小时</el-button
          >
        </div>
      </el-tab-pane>
    </el-tabs>
    <p class="pStyle">南京中网卫星通信股份有限公司</p>
  </div>
</template>

<script>
import Axios from "axios";
import moment from "moment";
import * as serviceApi from "../../../../common/service.config";
import { mapState } from "vuex";
Axios.defaults.withcredentials = true;

export default {
  inject: ["reload"],
  name: "FlowChart",
  props: {
    node: Object,
  },
  data() {
    return {
      form: {
        startTime: moment().subtract(1, "months").format("YYYY-MM-DD 00:00:00"),
        endTime: moment().format("YYYY-MM-DD 00:00:00"),
      },
      form2: {
        startTime: moment().subtract(1, "months").format("YYYY-MM-DD 00:00:00"),
        endTime: moment().format("YYYY-MM-DD 00:00:00"),
      },
      flowRateChart: null,
      flowRateHoursChart: null,
    };
  },
  computed: {
    ...mapState(["token"]),
    startTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.startTime
            ? time.getTime() > new Date(this.form.endTime).getTime()
            : false,
      };
    },
    endTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form.startTime).getTime()
            : false,
      };
    },
    startTimePicker2() {
      return {
        disabledDate: (time) =>
          this.form2.startTime
            ? time.getTime() > new Date(this.form2.endTime).getTime()
            : false,
      };
    },
    endTimePicker2() {
      return {
        disabledDate: (time) =>
          this.form2.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form2.startTime).getTime()
            : false,
      };
    },
  },
  mounted() {
    this.flowRateChart = this.$echarts.init(document.getElementById("total"));
    this.flowRateHoursChart = this.$echarts.init(
      document.getElementById("change")
    );
    let updateFlowRate = () => {
      this.flowRateChart.showLoading();
      let queryData = {
        startTime: moment().subtract(1, "months").format("YYYY-MM-DD"),
        endTime: moment().format("YYYY-MM-DD"),
      };
      if (sessionStorage.getItem("startTime"))
        queryData.startTime = sessionStorage.getItem("startTime");
      if (sessionStorage.getItem("endTime"))
        queryData.endTime = sessionStorage.getItem("endTime");
      this.form.startTime = moment(queryData.startTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      this.form.endTime = moment(queryData.endTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"tunnelNumber\\":\\"\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"token\\":\\"0\\"}","serviceCode":"queryFlowRateByDate","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.flowRateChart.hideLoading();
        this.initFlowRate(res.data);
      });
    };
    let updateFlowRateHours = () => {
      this.flowRateHoursChart.showLoading();
      let queryData = {
        startTime: moment().subtract(1, "months").format("YYYY-MM-DD"),
        endTime: moment().format("YYYY-MM-DD"),
        token: this.token,
      };
      if (sessionStorage.getItem("startTime"))
        queryData.startTime = sessionStorage.getItem("startTime");
      if (sessionStorage.getItem("endTime"))
        queryData.endTime = sessionStorage.getItem("endTime");
      this.form2.startTime = moment(queryData.startTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      this.form2.endTime = moment(queryData.endTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"tunnelNumber\\":\\"\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"token\\":\\"${queryData.token}\\"}","serviceCode":"queryFlowRateByDate","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.flowRateHoursChart.hideLoading();
        this.initFlowRateHours(res.data, queryData);
      });
    };
    let DataAnalysis = async () => {
      await updateFlowRate();
      await updateFlowRateHours();
    };
    DataAnalysis();
  },
  methods: {
    tabChange(tab) {
      this.$store.commit("setTabName7", tab.paneName);
    },
    initFlowRate(resultObj) {
      let list = resultObj.parameter.list;
      if (list != null && list != "undefined") {
        let xData = [],
          yData = [];
        for (let i = 0; i < list.length; i++) {
          xData.push(list[i].collectDate);
          yData.push(Math.abs(list[i].waterPressure).toFixed(1));
        }
        let chartOption = {
          title: {
            text: "流量",
            left: "center",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {
            top: 30,
            data: ["流量(m^3)"],
          },
          grid: {
            left: "10%",
            right: "20%",
            bottom: "3%",
            containLabel: true,
          },
          toolbox: {
            feature: {
              saveAsImage: {},
            },
            right: "5%",
          },
          xAxis: {
            name: "时间",
            type: "category",
            boundaryGap: true,
            data: xData,
          },
          yAxis: {
            name: "流量(m^3)",
            type: "value",
            axisLabel: {
              formatter: "{value} ",
            },
            min: "dataMin",
          },
          series: [
            {
              name: "流量(m^3)",
              type: "line",
              barGap: 0,
              color: ["#99cc66"],
              data: yData,
            },
          ],
        };
        this.flowRateChart.setOption(chartOption);
        this.flowRateChart.resize();
      }
    },
    search(startTime, endTime) {
      let queryData = {
        startTime,
        endTime,
      };
      sessionStorage.setItem("startTime", queryData.startTime);
      sessionStorage.setItem("endTime", queryData.endTime);
      this.reload();
    },
    query() {
      this.search(
        moment(this.form.startTime).format("YYYY-MM-DD"),
        moment(this.form.endTime).format("YYYY-MM-DD")
      );
    },
    week() {
      this.search(
        moment().subtract(7, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    month() {
      this.search(
        moment().subtract(31, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    all() {
      this.search(
        moment().subtract(1, "years").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    initFlowRateHours(resultObj, queryData) {
      let list = resultObj.parameter.list;
      if (list != null && list != "undefined") {
        let xData = [],
          yData = [];
        for (let i = 0; i < list.length; i++) {
          xData.push(list[i].collectDate);
          yData.push(Math.abs(list[i].waterPressure).toFixed(1));
        }
        let chartOption = {
          title: {
            text:
              this.node.label +
              "站点" +
              queryData.startTime +
              "至" +
              queryData.endTime +
              "内流量",
            left: "center",
          },
          tooltip: {
            trigger: "axis",
          },
          legend: {
            top: 30,
            data: ["流量"],
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          toolbox: {
            show: true,
            feature: {
              saveAsImage: { show: true },
            },
            right: "5%",
          },
          calculable: true,
          xAxis: [
            {
              type: "category",
              axisTick: {
                alignWithLabel: true,
              },
              data: xData,
            },
          ],
          yAxis: [
            {
              axisLabel: {
                formatter: "{value} mm",
              },
              type: "value",
            },
          ],
          series: [
            {
              name: "流量",
              type: "bar",
              barWidth: "60%",
              data: yData,
              itemStyle: {
                //通常情况下：
                normal: {
                  //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                  color: "rgb(32, 208, 254)",
                },
              },
            },
          ],
          label: {
            normal: {
              show: true,
              position: "top",
              textStyle: {
                color: "black",
              },
            },
          },
        };
        this.flowRateHoursChart.setOption(chartOption);
        this.flowRateHoursChart.resize();
      }
    },
    search2(startTime, endTime) {
      let queryData = {
        startTime,
        endTime,
      };
      sessionStorage.setItem("startTime", queryData.startTime);
      sessionStorage.setItem("endTime", queryData.endTime);
      this.reload();
    },
    query2() {
      this.search2(
        moment(this.form2.startTime).format("YYYY-MM-DD"),
        moment(this.form2.endTime).format("YYYY-MM-DD")
      );
    },
    week2() {
      this.search2(
        moment().subtract(7, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    month2() {
      this.search2(
        moment().subtract(31, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    all2() {
      this.search2(
        moment().subtract(1, "years").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    time(token) {
      this.flowRateHoursChart.showLoading();
      let queryData = {
        startTime: moment(this.form2.startTime).format("YYYY-MM-DD"),
        endTime: moment(this.form2.endTime).format("YYYY-MM-DD"),
      };
      queryData.token = token;
      this.$store.dispatch("getToken", token);
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"tunnelNumber\\":\\"\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"token\\":\\"${queryData.token}\\"}","serviceCode":"queryFlowRateByDate","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.flowRateHoursChart.hideLoading();
        this.initFlowRateHours(res.data, queryData);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.pStyle {
  position: absolute;
  bottom: 1%;
  right: 2%;
}
.chart {
  width: 1600px;
  height: 75vh;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>